import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

export const genRandomId = () => {
	return Math.random().toString(36).substr(2, 9) + Date.now().toString(36)
}
export const isNewVersion = () => {
	const url = `//${window.location.host}/manifest.json?id=${genRandomId()}`
	try {
		axios.get(url).then((res) => {
			const { version } = res.data
			const localVersion = localStorage.getItem('version')
			const versionTip = localStorage.getItem('version_tip') || 0
			if (localVersion && localVersion !== version && versionTip == 0) {
				localStorage.setItem('version_tip', 1)
				ElMessageBox.confirm('发现新的版本，请刷新页面后使用！?', '提示', {
					confirmButtonText: '立即刷新',
					cancelButtonText: '稍后刷新',
					type: 'warning',
				})
					.then(() => {
						window.location.reload()
						localStorage.setItem('version', version)
						localStorage.setItem('version_tip', 0)
					})
					.catch(() => {})
			} else {
				localStorage.setItem('version', version)
				localStorage.setItem('version_tip', 0)
			}
		})
	} catch (e) {
	}
}
